package com.mystnihon.freeremote.ui.fragment;

import java.io.File;
import java.io.FilenameFilter;
import java.net.URI;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockListFragment;
import com.mystnihon.freeremote.R;
import com.mystnihon.freeremote.manager.file.FileManager;
import com.mystnihon.freeremote.manager.file.NotMountedStorageException;
import com.mystnihon.freeremote.ui.UploadActivity;

public class FileChooserFragment extends SherlockListFragment {
	private static final String TAG = UploadActivity.class.getSimpleName();

	private FileManager fileMng;
	private FileAdapter mAdapter;
	private FilenameFilter mFilter;

	enum FilterType {
		All, Torrent, Directory
	}

	public static FileChooserFragment newInstance() {

	    FileChooserFragment fragment = new FileChooserFragment();

        return fragment;
    }
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		Bundle intent = getArguments();
		if (intent != null) {
			FilterType filter = (FilterType) intent.getSerializable(UploadActivity.EXTRA_NAME_FILTER);
			// mFilter = new NameFilter(mNameFilter);
			switch (filter) {
				case All:
					mFilter = null;
					break;
				case Directory:
					mFilter = FileManager.directoryOnly;
					break;
				case Torrent:
					mFilter = FileManager.torrentFilter;
					break;
			}
		}

		mAdapter = new FileAdapter(getSherlockActivity().getApplicationContext());
		setListAdapter(mAdapter);
		getListView().setOnItemClickListener(mAdapter);
		try {
			fileMng = new FileManager(getSherlockActivity().getApplicationContext());
			mAdapter.setFiles(getFiles(), fileMng.getExternalStorageDirectory());

		} catch (NotMountedStorageException e) {
			Log.w(TAG, "Erreur while getting files" + e.getStorageState());

		}
	}

	private ArrayList<File> getFiles() {
		if (mFilter != null) {
			return fileMng.listExternalStorageBaseFile(mFilter);
		} else
			return fileMng.listExternalStorageBaseFile();

	}

	class FileParent extends File {
		/**
		 * 
		 */
		private static final long serialVersionUID = -3866071983969330216L;

		public FileParent(String dirPath, String name) {
			super(dirPath, name);
		}

		public FileParent(File dir, String name) {
			super(dir, name);
		}

		public FileParent(String path) {
			super(path);
		}

		public FileParent(URI uri) {
			super(uri);
		}

		public String getName() {
			return "..";
		}
	}

	class ViewHolder {
		TextView mFileName;
		TextView mFileExtension;
		ImageView mIcon;
	}

	class FileAdapter extends BaseAdapter implements AdapterView.OnItemClickListener {
		LayoutInflater inflater;
		ArrayList<File> files;
		File currentFile;

		public FileAdapter(Context context) {
			files = new ArrayList<File>();
			inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public void setFiles(ArrayList<File> supFiles, File currentFile) {
			if (supFiles != null) {
				this.currentFile = currentFile;
				files.clear();
				files.addAll(supFiles);
				notifyDataSetChanged();

			}
		}

		@Override
		public int getCount() {
			return files.size() + 1;
		}

		@Override
		public File getItem(int position) {
			return files.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = inflater.inflate(R.layout.listitem_file, null);
				holder.mFileName = (TextView) convertView.findViewById(R.id.listitem_filename);
				holder.mFileExtension = (TextView) convertView.findViewById(R.id.listitem_fileextension);
				holder.mIcon = (ImageView) convertView.findViewById(R.id.listitem_icon);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			File file = null;
			if (position == 0) {
				file = currentFile.getParentFile();
				holder.mFileName.setText("..");
			} else {
				file = getItem(position - 1);
				holder.mFileName.setText(file.getName());
			}

			if (file.isDirectory()) {
				holder.mIcon.setImageResource(R.drawable.collections_collection);
			} else {
				holder.mIcon.setImageResource(R.drawable.collections_view_as_list);
			}
			return convertView;
		}

		@Override
		public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
			if (position == 0) {
				goBack();
			} else {
				final File file = getItem(position - 1);
				if (file.isDirectory()) {
					setFiles(fileMng.listDirectoryFile(file), file);
				} else {
					Uri uri = Uri.fromFile(file);

					getSherlockActivity().setResult(Activity.RESULT_OK,
							new Intent().putExtra(UploadActivity.EXTRA_RESPONSE_URI, uri));
					getSherlockActivity().finish();
				}
			}
		}

		public boolean goBack() {
			if (currentFile.equals(fileMng.getExternalStorageDirectory())) {
				return false;
			} else {
				File parent = currentFile.getParentFile();
				setFiles(fileMng.listDirectoryFile(parent), parent);
				return true;
			}
		}

	}

	public boolean goBack() {
		return mAdapter.goBack();
	}
}
